package com.hiof.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.dsi.ant.AntInterface;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.hiof.Configuration;
import com.hiof.R;
import com.hiof.antplus.AntPlusManager;
import com.hiof.connection.observers.BluetoothConnectionManager;
import com.hiof.data.MoraService;
import com.hiof.location.GPSManager;
import com.hiof.location.GpsMangerFactory;
import com.hiof.location.earcon.EncourageNotificationManager;
import com.hiof.media.CameraIntent;
import com.hiof.media.MediaFilesObserver;
import com.hiof.media.MediaIntent;
import com.hiof.menus.NavigationMenu;
import com.hiof.overlays.AthletePositionOverlay;
import com.hiof.overlays.MapPointsManager;
import com.hiof.overlays.OwnOverlay;
import com.hiof.overlays.TripRouteOverlay;
import com.hiof.servercommunication.RestFulServiceManager;
import com.hiof.servercommunication.background.job.JobThreadQueue;
import com.hiof.servercommunication.background.job.TimerJobManager;
import com.hiof.servercommunication.background.job.managers.AbstractBackgroundThreadManager;
import com.hiof.servercommunication.background.job.managers.BackgroundManagerFactory;
import com.hiof.servercommunication.receive.beans.GeoPoint;
import com.hiof.settings.SettingManager;
import com.hiof.settings.user.TypeOfAttendant;
import com.hiof.settings.user.UserConfiguration;
import com.hiof.utility.Utility;
import com.hiof.voiceguide.Speaker;

/**
 * Created with IntelliJ IDEA.
 * User: manish
 * Date: 6/28/12
 * Time: 6:43 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainActivitySupport extends MapActivity {
    MediaFilesObserver mediaFilesObserver;
    private MapView mapView;
    private MapController mapController;
    private OwnOverlay ownOverlay;
    private AthletePositionOverlay athletePositionOverlay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Configuration.getInstance().setCurrentContext(this);
        setContentView(R.layout.main_support);
        initLocationFunctionality();
        drawRaceRoute();
        setUpJobThread();

        Speaker.initialize(this);
        startMediaObserver();

        Utility.debug(this.getClass().getName(), "Activity lifecycle: Start Main Activity ");
    }

    private void startMediaObserver() {
        mediaFilesObserver = MediaFilesObserver.getInstance();
        mediaFilesObserver.startWatching();
    }

    private void setUpJobThread() {
        //start job thread
        JobThreadQueue jobThreadQueue = JobThreadQueue.getInstance();
        jobThreadQueue.startThread();
        AbstractBackgroundThreadManager threadManager = BackgroundManagerFactory.getBackgroundManager(TypeOfAttendant.SUPPORT);
        threadManager.setUp();
        //TODO: register observer here
        threadManager.registerListener(MoraService.getInstance());
        //TODO: if the user is athlete register teammatesoverlay
        threadManager.registerListener(athletePositionOverlay);
    }

    private void drawRaceRoute() {
        TripRouteOverlay tripRouteOverlay = new TripRouteOverlay(this);
        mapView.getOverlays().add(tripRouteOverlay);
    }

    private void initLocationFunctionality() {
        //initialize Location updates
        GPSManager gpsManager = GpsMangerFactory.getGpsManager();
        mapView = (MapView) findViewById(R.id.mapview);
        mapController = mapView.getController();
        mapView.getController().setZoom(15);
        mapView.setBuiltInZoomControls(false);
        GeoPoint initGeoPoint = gpsManager.getLatestLocation();

        ownOverlay = new OwnOverlay(getResources(), initGeoPoint);
        gpsManager.registerListener(ownOverlay);
        /*
            teammatePositionOverlay is registered in the jobthread manager
            as it has to listen the location updates from the server
         */
        athletePositionOverlay = new AthletePositionOverlay(getResources());

        mapView.getOverlays().add(ownOverlay);
        mapView.getOverlays().add(athletePositionOverlay);
        mapController.animateTo(initGeoPoint.getGoogleGeoPoint());
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.map_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.setting:
                showPreferences();
                break;
            case R.id.signout:
                signOut();
                break;
            case R.id.exit:
                exit();
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        destroyServices();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    public void onMenuButtonClick(View v) {
        int key = v.getId();
        switch (key) {
            case R.id.cancel_button:
                NavigationMenu.getInstance().cancel();
                break;
            case R.id.select_button:
                NavigationMenu.getInstance().select();
                break;
            case R.id.next_button:
                NavigationMenu.getInstance().next();
                break;
            case R.id.previous_button:
                NavigationMenu.getInstance().previous();
                break;
            case R.id.camera_button:
                MediaIntent camera = new CameraIntent();
                Configuration.getInstance().getCurrentContext().startActivity(camera);
                break;
        }
    }

    private void signOut() {
        SettingManager.getInstance().setUsername("");
        SettingManager.getInstance().setPassword("");
        TimerJobManager.getInstance().stopTimerJob();
        exit();
    }

    private void showPreferences() {
        startActivity(new Intent(this, Preferences.class));
    }

    private void exit() {
        JobThreadQueue.getInstance().clearJobQueue();
        JobThreadQueue.getInstance().stopThread();
        unregisteredObservers();
        destroyServices();
        finish();
    }

    private void unregisteredObservers() {
        AbstractBackgroundThreadManager threadManager = BackgroundManagerFactory.getBackgroundManager(TypeOfAttendant.ATHLETE);
        threadManager.removeListener(MoraService.getInstance());


        GpsMangerFactory.getGpsManager().removeListener(ownOverlay);
        GpsMangerFactory.getGpsManager().removeListener(EncourageNotificationManager.getInstance());
        mediaFilesObserver.stopWatching();
    }

    private void destroyServices() {
        RestFulServiceManager.getInstance().shutDownService();

        Configuration.getInstance().destroy();
        BluetoothConnectionManager.getInstance().destroy();
        GpsMangerFactory.getGpsManager().destroy();
        EncourageNotificationManager.getInstance().destroy();
        MediaFilesObserver.getInstance().destroy();
        NavigationMenu.getInstance().destroy();
        SettingManager.getInstance().destroy();
        MapPointsManager.getInstane().destroy();
        UserConfiguration.getInstance().destroy();
        MoraService.getInstance().destroy();
        Speaker.stop();
    }
}
